package com.ysc.plugin.utility.photo.clip

import android.app.Activity
import android.content.ContentValues
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Environment
import android.provider.MediaStore
import android.util.Log
import androidx.core.content.FileProvider
import androidx.core.net.toUri
import com.ysc.plugin.common.ActivityRequestCode
import com.ysc.plugin.common.abstract.ManagerModule
import org.json.JSONObject
import java.io.File
import java.io.OutputStream

class ClipPhoto(activity: Activity): ManagerModule() {
    private val mActivity: Activity = activity
    private var mUri: Uri? = null
    private var mImagePath: String = ""

    fun photoClip(data:String) {
        var filePath = ""
        if (data!=null && !data.isEmpty()){
            var decodeData = JSONObject(data)
            if(decodeData.has("filePath"))
                filePath = decodeData["filePath"] as String
        }
        if (filePath.isEmpty()) {
            return
        }
        mImagePath = filePath
        var file = File(filePath)
        if(!file.exists())
            return
        mUri = file.toUri()

        var intent = Intent("com.android.camera.action.CROP")
        intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
        intent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
        intent.setDataAndType(mUri, "image/*")
        // 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", true)
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1)
        intent.putExtra("aspectY", 1)
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 100)
        intent.putExtra("outputY", 100)
        intent.putExtra("circleCrop", true)

        //intent.putExtra("return-data", false)

        var extStorageDirectory = mActivity.getExternalFilesDir(Environment.DIRECTORY_PICTURES).toString()
        var filename:String = "999.jpeg"

        if(!file.exists())
            file.createNewFile()
        var t = FileProvider.getUriForFile(
            mActivity,
            mActivity.packageName + ".fileprovider",
            file
        )
        var tyri = Uri.fromFile(file)
        intent.putExtra(MediaStore.EXTRA_OUTPUT, t)
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString())
        setActivityResult(true)
        mActivity.startActivityForResult(intent, ActivityRequestCode.REQUEST_CLIP_PHOTO.ordinal)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if(resultCode == Activity.RESULT_OK) {
            if (requestCode == ActivityRequestCode.REQUEST_CLIP_PHOTO.ordinal) {
                var contentResolver = mActivity.contentResolver
                var contentValues = ContentValues()
                //contentValues.put(MediaStore.Images.Media.RELATIVE_PATH, "Pictures/demo")
                contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, "999.jpeg")
                contentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
                var uri = contentResolver.insert(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    contentValues
                )
                var outputStream: OutputStream?
                try {
                    outputStream = uri?.let { contentResolver.openOutputStream(it) }

                    var bitmap = BitmapFactory.decodeFile(mImagePath)

                    bitmap?.compress(Bitmap.CompressFormat.JPEG, 100, outputStream)
                    outputStream?.flush()
                    outputStream?.close()

                } catch (e: Exception) {
                    e.printStackTrace()
                    Log.d("savePictureToAlbum", "Exception=" + e.message)
                }
                setActivityResult(false)
            }
        }
    }

    override fun onDestroy() {

    }

    override fun getHelp(): String {
        return "command:photo;\n" +
                "category:ClipPhoto;\n" +
                "operate:{\n" +
                "  photoClip:进行图片裁剪,\n" +
                "    parameter:{\n" +
                "      filePath:图片文件所在路径\n" +
                "    }\n" +
                "}"
    }

    override fun getName(): String {
        return "ClipPhoto"
    }

    override fun getVersion(): String {
        return "1.0.0"
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
//        setPermissionsResult(false)
//        if(requestCode == PermissionsRequestCode.REQUEST_WRITE_EXTERNAL_STORAGE.ordinal && grantResults[0] == PackageManager.PERMISSION_GRANTED)
//        {
//            photoClip(mUri)
//        }
    }
}